import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '../api'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore('user', () => {
  const router = useRouter()
  const token = ref(localStorage.getItem('token'))
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const isAuthenticated = ref(!!localStorage.getItem('token'))

  const login = async (credentials) => {
    try {
      const response = await api.post('/login', credentials)
      token.value = response.data.token
      user.value = response.data.user
      isAuthenticated.value = true

      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))

      return true
    } catch (error) {
      console.error('登录失败:', error)
      logout()
      return false
    }
  }

  const logout = () => {
    token.value = null
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  }

  const checkAuth = async () => {
    if (!token.value) {
      isAuthenticated.value = false
      return false
    }

    try {
      const response = await api.get('/profile')
      user.value = response.data.user
      isAuthenticated.value = true
      return true
    } catch (error) {
      console.error('验证失败:', error)
      logout()
      return false
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
})
